package io.jmqtt.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.mqtt.MqttConnAckMessage;
import io.netty.handler.codec.mqtt.MqttConnectMessage;
import io.netty.handler.codec.mqtt.MqttConnectReturnCode;
import io.netty.handler.codec.mqtt.MqttMessageBuilders;

/**
 * mqtt 链接handler
 * 
 * @author chenhua
 *
 */
public class MqttConnectHandler extends SimpleChannelInboundHandler<MqttConnectMessage> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, MqttConnectMessage msg) throws Exception {
		// 校验clientid
		if (!validClientId(ctx, msg)) {
			return;
		}
		// 标志是否接管
		ctx.channel().attr(AttributeKeys.MQTT_TAKEN_OVER).set(false);
		// 回发 CONNECT_ACK
		// 此处就可以做链接验证 TODO
		MqttConnAckMessage connAck = MqttMessageBuilders.connAck().returnCode(MqttConnectReturnCode.CONNECTION_ACCEPTED)
				.build();
		ctx.writeAndFlush(connAck);
	}

	/**
	 * 校验ClientId
	 * 
	 * @param ctx
	 * @param msg
	 * @return
	 */
	private boolean validClientId(ChannelHandlerContext ctx, MqttConnectMessage msg) {
		// TODO Auto-generated method stub
		return true;
	}

}
